<template>
  <el-card
    class="form-container"
    shadow="never"
  >
    <el-form
      :model="content"
      :rules="rules"
      ref="contentFrom"
      label-width="150px"
    >
      <el-form-item
        label="形式："
        prop="type"
      >
        <el-radio-group v-model="content.type">
          <el-radio label="1">图文（不含视频）</el-radio>
          <el-radio label="2">含视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="content.type === '2'"
        label="标清："
        prop="videoAddrLow"
      >
        <el-input
          v-model="content.videoAddrLow"
          class="input-width"
          placeholder="请输入视频url"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="content.type === '2'"
        label="高清："
        prop="videoAddrHigh"
      >
        <el-input
          v-model="content.videoAddrHigh"
          class="input-width"
          placeholder="请输入视频url"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="标题："
        prop="title"
      >
        <el-input
          v-model="content.title"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="来源："
        prop="source"
      >
        <el-input
          v-model="content.source"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-show="content.type === '2'"
        label="正文："
        prop="content"
      >
        <el-input
          type="textarea"
          :rows="8"
          placeholder="请输入内容"
          v-model="content.content"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="正文："
        v-show="content.type === '1'"
        prop="content"
      >
        <div
          ref="editor"
          class="editor-wrapper"
        ></div>
      </el-form-item>
      <el-form-item
        label="渠道："
        prop="channel"
      >
        <el-checkbox-group
          v-model="content.channel"
          @change="handleCheckedChannelChange"
        >
          <el-checkbox
            v-for="item in channelList"
            :label="parseInt(item.commonCode)"
            :key="item.commonCode"
          >{{ item.commonDesc }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        label="位置："
        prop="classified"
      >
        <el-table
          :header-cell-style="headerStyle"
          ref="tableRef"
          :data="classifiedType"
          style="width: 100%;"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column
            align="center"
            width="60"
          >
            <template slot-scope="scope">
              <el-radio
                :label="scope.row.commonCode"
                v-model="content.classified"
                @click.native="getRadio(scope.$index,scope.row)"
              >{{ "" }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            align="center"
          >
            <template slot-scope="scope">{{ scope.row.commonDesc }}</template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item
        label="生效时间："
        :rules="[
          { required: true, message: '请选择生效时间', trigger: 'change' }
        ]"
      >
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="dateRangeChange"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit('contentFrom')"
        >提交</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import SingleUpload from '@/components/Upload/singleUpload'
import WEditor from 'wangeditor'
import moment from 'moment'
import {
  contentGetById,
  contentSave,
  contentUpdate,
  commonList
} from '@/api/content'

const defaultContent = {
  type: '1',
  title: null,
  videoUrl: null,
  source: null,
  // channel: [],
  channel: [], // 不可改
  classified: null,
  content: null,
  videoAddrLow: '',
  videoAddrHigh: '',
  // dateRange: [],
  // dateRange: [moment(), moment("2099-12-31")],
  // stime: moment().format(),
  // etime: moment("2099-12-31").format(),
  stime: '',
  etime: ''
}
export default {
  name: 'AddContent',
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      parentId: 0,
      dateRange: [],
      content: Object.assign({}, defaultContent),
      channelList: [],
      classifiedType: [],
      headerStyle: {
        background: ' #f2f6fc',
        height: '20px',
        'line-height': '20px'
      },
      isChecked: false,
      pickerOptions: {},
      rules: {
        type: [{ required: true, message: '请选择形式', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        videoAddrLow: [
          { required: true, message: '请输入视频URL', trigger: 'blur' }
        ],
        videoAddrHigh: [
          { required: true, message: '请输入视频URL', trigger: 'blur' }
        ],
        source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
        channel: [{ required: true, message: '请选择渠道', trigger: 'blur' }],
        classified: [
          { required: true, message: '请选择位置', trigger: 'blur' }
        ],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getSourseType()
    this.getChannelType()
  },
  mounted () {
    if (this.isEdit) {
      contentGetById({ id: this.$route.query.id }).then((response) => {
        this.content = response.data
        this.content.channel = Object.assign(
          response.data.channel,
          defaultContent
        )
        console.log(response.data)

        if (this.content.type === '2') {
          // 处理视频清晰度
          this.content.videoUrl = eval('(' + this.content.videoUrl + ')')
          this.content.videoAddrLow = this.content.videoUrl[0]
          this.content.videoAddrHigh = this.content.videoUrl[1]
        }
        this.dateRange = [this.content.stime, this.content.etime]
        // console.log(this.dateRange);
        this.initEditor(this.content.content)
        if (this.content.channel.length == 1) {
          const num = parseInt(this.content.channel)
          this.content.channel = []
          this.content.channel.push(num)
          // console.log(this.content.channel);
        } else {
          this.content.channel = eval('(' + this.content.channel + ')')
        }
      })
    } else {
      this.content = Object.assign({}, defaultContent)
      this.initEditor('')
    }
  },
  methods: {
    initEditor (content) {
      this.editor = new WEditor(this.$refs.editor)
      // this.editor.customConfig.debug = true
      this.editor.customConfig.uploadImgServer = '/zdmanage/upload'
      this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
      // this.editor.customConfig.uploadImgParams = {
      //   busiType: 'rich'
      // }
      this.editor.customConfig.customAlert = function (info) {
        // message.error(info)
      }
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result) {
          if (!result.data) {
            // message.error(result.resultMessage)
          } else {
            insertImg(result.data)
          }
        }
      }
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        // 'link', // 插入链接
        // 'list', // 列表
        'justify', // 对齐方式
        // 'quote', // 引用
        // 'emoticon', // 表情
        'image', // 插入图片
        // 'table', // 表格
        // 'video', // 插入视频
        // 'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
      // this.editor.customConfig.onchange = (html) => {
      //   this.editorContent = html
      //   this.$emit('change', this.editorContent)
      // }
      this.editor.create()
      this.editor.txt.html(content)
    },
    getChannelType () {
      const params = {
        commonType: 'channel'
      }
      // 获取枚举
      commonList(params).then((response) => {
        // const list = response.data;
        // console.log(response.data);
        this.channelList = response.data
      })
    },
    getSourseType () {
      const params = {
        commonType: 'classified'
      }
      // 获取枚举
      commonList(params).then((response) => {
        // const list = response.data;
        // console.log(response.data);
        this.classifiedType = response.data
      })
    },
    handleSelectionChange (val) {},
    getRadio (index, row) {
      // 获取选中数据
      console.log(row)
      this.content.classified = row.commonCode
      // console.log(this.content)
    },
    onSubmit (formName) {
      if (this.content.type === '1') {
        this.content.content = this.editor.txt.html()
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.isEdit) {
              const { videoAddrLow, videoAddrHigh } = this.content
              this.content.channel = eval('(' + this.content.channel + ')')

              console.log(this.content.channel)
              // console.log(this.content.channel.join());
              const params = {
                id: this.$route.query.id,
                ...this.content,
                videoUrl: JSON.stringify([videoAddrLow, videoAddrHigh])
              }
              console.log(params)
              contentUpdate(params).then((response) => {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            } else {
              const { videoAddrLow, videoAddrHigh } = this.content
              this.content.channel = eval('(' + this.content.channel + ')')

              const params = {
                ...this.content,
                videoUrl: JSON.stringify([videoAddrLow, videoAddrHigh])
                // id: 0,
              }
              console.log(params)
              contentSave(params).then((response) => {
                this.$refs[formName].resetFields()
                this.resetForm(formName)
                console.log(response.data)
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleCheckedChannelChange (val) {
      console.log(val)
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.content = Object.assign({}, defaultContent)
    },
    back () {
      this.$router.go(-1)
    },
    dateRangeChange (e) {
      this.content.stime = moment(e[0]).format()
      this.content.etime = moment(e[1]).format()
      console.log(this.content)
    }
  }
}
</script>

<style scoped>
.form-container {
  position: relative;
  z-index: 0;
  width: 800px;
}
table.el-table__header thead {
  background: #f2f6fc !important;
  height: 30px;
  line-height: 30px;
}
</style>
